package hos.kotlin

/**
 * <p>Title: PasswordChecker </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-07-23 19:53
 * @version : 1.0
 */
class PasswordChecker(
    // 包含大写字母
    private val upperCase: Boolean = false,
    private val lowerCase: Boolean = false, // 包含小写字母
    private val letter: Boolean = false, // 包含字母
    private val digit: Boolean = false, // 包含数字
    private val special: Boolean = false, // 包含特殊字符
    private val minLength: Int = 8, // 最小长度
    private val maxLength: Int = 30, // 最大长度
    private val specialCharSet: MutableSet<Char> = mutableSetOf<Char>(
        '~', '`', '!', '@', '#', '$', '%', '^',
        '&', '*', '(', ')', '-', '_', '+', '=',
        '{', '[', '}', ']', '|', '\\', ':', ';',
        '"', '\'', '<', ',', '>', '.', '?', '/',
    ),// 特殊字符集合
) {

    // 特殊字符集合
//    private val specialCharSet by lazy {
//        mutableSetOf<Char>(
//            '~', '`', '!', '@', '#', '$', '%', '^',
//            '&', '*', '(', ')', '-', '_', '+', '=',
//            '{', '[', '}', ']', '|', '\\', ':', ';',
//            '"', '\'', '<', ',', '>', '.', '?', '/',
//        )
//    }

    /**
     * 密码符合规则，返回true
     */
    fun check(password: String?): Boolean {
        if ((password == null || password.length < this.minLength) || password.length > this.maxLength) {
            // 长度不符合
            return false
        }
        var containUpperCase = false
        var containLowerCase = false
        var containLetter = false
        var containDigit = false
        var containSpecial = false
        for (ch in password.toCharArray()) {
            if (Character.isUpperCase(ch)) {
                containUpperCase = true
                containLetter = true
            } else if (Character.isLowerCase(ch)) {
                containLowerCase = true
                containLetter = true
            } else if (Character.isDigit(ch)) {
                containDigit = true
            } else if (this.specialCharSet.contains(ch)) {
                containSpecial = true
            } else {
                // 非法字符
                return false
            }
        }
        if (this.upperCase && !containUpperCase) {
            return false
        }
        if (this.lowerCase && !containLowerCase) {
            return false
        }
        if (this.letter && !containLetter) {
            return false
        }
        if (this.digit && !containDigit) {
            return false
        }
        if (this.special && !containSpecial) {
            return false
        }
        return true
    }

}